<template>
  <div class="system-bg">
    <el-card class="user-card" shadow="hover">
      <div slot="header" class="card-header-vertical">
        <div class="header-title">家族动态管理</div>
        <div class="header-btn-group right">
          <el-button class="add-btn" type="primary" @click="onShowAdd">
            <i class="el-icon-plus"></i> 新增动态
          </el-button>
        </div>
      </div>
      <el-table :data="list" style="width:100%" class="user-table" highlight-current-row>
        <el-table-column prop="clanName" label="家族名称" width="140" />
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="type" label="类型" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.type==='news'" type="info">新闻</el-tag>
            <el-tag v-else-if="scope.row.type==='event'" type="success">事件</el-tag>
            <el-tag v-else-if="scope.row.type==='story'" type="warning">故事</el-tag>
            <el-tag v-else>其他</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="authorName" label="作者" width="120" />
        <el-table-column prop="viewCount" label="浏览" width="80" />
        <el-table-column prop="likeCount" label="点赞" width="80" />
        <!-- <el-table-column prop="createdAt" label="创建时间" width="160" /> -->
        <el-table-column label="操作" width="240">
          <template slot-scope="scope">
            <div class="action-btn-group" style="overflow:visible;">
              <el-button size="mini" class="edit-btn" @click="edit(scope.row)">编辑</el-button>
              <el-button size="mini" class="delete-btn" @click="remove(scope.row)">删除</el-button>
              <el-button size="mini" class="detail-btn" @click="viewDetail(scope.row)">详情</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :total="total"
        :page-size="size"
        :current-page="current"
        @current-change="load"
        @size-change="handleSizeChange"
        layout="total, prev, pager, next, jumper, ->, sizes"
        :page-sizes="[10, 20, 50, 100]"
        class="user-pagination"
      />
    </el-card>
    <el-dialog :visible.sync="showAdd" title="新增动态" class="fade-dialog custom-dialog" :close-on-click-modal="false" width="700px">
      <el-form :model="form" label-width="90px" class="dialog-form">
        <el-form-item label="家族" class="nowrap-label">
          <el-select v-model="form.clanId" placeholder="请选择家族" style="width:100%">
            <el-option v-for="clan in clanList" :key="clan.id" :label="clan.name" :value="clan.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="标题"><el-input v-model="form.title" /></el-form-item>
        <el-form-item label="类型"><el-select v-model="form.type"><el-option label="新闻" value="news" /><el-option label="事件" value="event" /><el-option label="故事" value="story" /></el-select></el-form-item>
        <el-form-item label="内容"><el-input v-model="form.content" type="textarea" :rows="4" /></el-form-item>
        <el-form-item label="图片" class="nowrap-label">
          <el-upload
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
            :on-error="handleImageError"
            :headers="getUploadHeaders()"
            accept="image/*"
            class="photo-upload">
            <div v-if="!form.image" class="photo-upload-square">
              <i class="el-icon-plus photo-uploader-icon"></i>
            </div>
            <img v-else :src="getImageUrl(form.image)" class="photo-preview" @click="previewImage(form.image)" />
          </el-upload>
          <el-button v-if="form.image" size="mini" type="danger" @click="removeImage" style="margin-left: 12px;">删除图片</el-button>
        </el-form-item>
<!--        <el-form-item label="作者" class="nowrap-label">-->
<!--          <el-input v-model="form.authorId" :disabled="true" />-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAdd=false">取消</el-button>
        <el-button type="primary" @click="add">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="showEdit" title="编辑动态" class="fade-dialog custom-dialog" :close-on-click-modal="false" width="700px">
      <el-form :model="form" label-width="90px" class="dialog-form">
        <el-form-item label="家族" class="nowrap-label">
          <el-select v-model="form.clanId" placeholder="请选择家族" style="width:100%">
            <el-option v-for="clan in clanList" :key="clan.id" :label="clan.name" :value="clan.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="标题"><el-input v-model="form.title" /></el-form-item>
        <el-form-item label="类型"><el-select v-model="form.type"><el-option label="新闻" value="news" /><el-option label="事件" value="event" /><el-option label="故事" value="story" /></el-select></el-form-item>
        <el-form-item label="内容"><el-input v-model="form.content" type="textarea" :rows="4" /></el-form-item>
        <el-form-item label="图片" class="nowrap-label">
          <el-upload
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
            :on-error="handleImageError"
            :headers="getUploadHeaders()"
            accept="image/*"
            class="photo-upload">
            <div v-if="!form.image" class="photo-upload-square">
              <i class="el-icon-plus photo-uploader-icon"></i>
            </div>
            <img v-else :src="getImageUrl(form.image)" class="photo-preview" @click="previewImage(form.image)" />
          </el-upload>
          <el-button v-if="form.image" size="mini" type="danger" @click="removeImage" style="margin-left: 12px;">删除图片</el-button>
        </el-form-item>
<!--        <el-form-item label="作者" class="nowrap-label">-->
<!--          <el-input v-model="form.authorId" :disabled="true" />-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showEdit=false">取消</el-button>
        <el-button type="primary" @click="update">保存</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="showDetail" title="动态详情" class="fade-dialog custom-dialog" :close-on-click-modal="false" width="700px">
      <el-descriptions :title="form.title" :column="2" border>
        <el-descriptions-item label="家族">{{ form.clanName }}</el-descriptions-item>
        <el-descriptions-item label="类型">
          <el-tag v-if="form.type==='news'" type="info">新闻</el-tag>
          <el-tag v-else-if="form.type==='event'" type="success">事件</el-tag>
          <el-tag v-else-if="form.type==='story'" type="warning">故事</el-tag>
          <el-tag v-else>其他</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="作者">{{ form.authorName }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ form.createdAt }}</el-descriptions-item>
        <el-descriptions-item label="内容" :span="2">
          <div style="white-space:pre-line;">{{ form.content }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="图片" :span="2">
          <div v-if="form.image">
            <img :src="getImageUrl(form.image)" class="photo-preview" style="max-width:180px;max-height:120px;cursor:pointer;" @click="previewImage(form.image)" />
          </div>
          <div v-else>无</div>
        </el-descriptions-item>
        <el-descriptions-item label="浏览">{{ form.viewCount }}</el-descriptions-item>
        <el-descriptions-item label="点赞">{{ form.likeCount }}</el-descriptions-item>
      </el-descriptions>
      <div class="detail-footer">
        <el-button class="outline-btn" @click="showDetail=false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getFamilyNewsList,
  getFamilyNewsDetail,
  addFamilyNews,
  updateFamilyNews,
  deleteFamilyNews
} from '@/api/familynews';
import { getClanList } from '@/api/clan';
import store from '@/store';
export default {
  data() {
    return {
      list: [],
      total: 0,
      size: 10,
      current: 1,
      showAdd: false,
      showEdit: false,
      showDetail: false,
      form: {},
      searchForm: { clanId: '', type: '' },
      clanList: [],
      uploadUrl: '/api/v1/upload/member-photo',
    };
  },
  created() { this.load(); this.loadClans(); },
  methods: {
    async load(page = 1) {
      this.current = page;
      const params = { ...this.searchForm, page, size: this.size };
      const data = await getFamilyNewsList(params);
      this.list = data.records || data.list || [];
      this.total = data.total || 0;
      this.size = data.size || 10;
      this.current = data.current || page;
    },
    async loadClans() {
      const data = await getClanList({ page: 1, size: 100 });
      this.clanList = data.records || data.list || [];
    },
    handleSizeChange(newSize) {
      this.size = newSize;
      this.load(1);
    },
    onShowAdd() {
      this.form = { clanId: '', title: '', type: '', content: '', image: '', authorId: store.state.user ? store.state.user.id : '', authorName: store.state.user ? (store.state.user.nickname || store.state.user.username) : '' };
      this.showAdd = true;
    },
    async add() {
      await addFamilyNews(this.form);
      this.$message.success('新增动态成功');
      this.showAdd = false;
      this.load();
    },
    edit(row) {
      this.form = { ...row, authorId: store.state.user ? store.state.user.id : '', authorName: store.state.user ? (store.state.user.nickname || store.state.user.username) : '' };
      this.showEdit = true;
    },
    async update() {
      await updateFamilyNews(this.form);
      this.$message.success('更新动态成功');
      this.showEdit = false;
      this.load();
    },
    async remove(row) {
      try {
        await this.$confirm('确定要删除该动态吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        await deleteFamilyNews(row.id);
        this.$message.success('删除动态成功');
        this.load();
      } catch (e) {
        if (e !== 'cancel') {
          this.$message.error('删除动态失败');
        }
        // 用户点取消不提示
      }
    },
    async viewDetail(row) {
      const data = await getFamilyNewsDetail(row.id);
      this.form = { ...data };
      this.showDetail = true;
    },
    getUploadHeaders() {
      return {
        'Authorization': 'Bearer ' + (localStorage.getItem('token') || '')
      };
    },
    getImageUrl(path) {
      if (!path) return '';
      if (/^https?:/.test(path)) return path;
      return path;
    },
    previewImage(imagePath) {
      if (imagePath) {
        const imageUrl = this.getImageUrl(imagePath);
        this.$alert(`<img src="${imageUrl}" style="max-width:100%;max-height:400px;" />`, '图片预览', {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '关闭'
        });
      }
    },
    handleImageSuccess(response) {
      if (response.code === 0) {
        this.form.image = response.data || response.url;
        this.$message.success('图片上传成功');
      } else {
        this.$message.error(response.msg || '图片上传失败');
      }
    },
    beforeImageUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }
      if (!isLt5M) {
        this.$message.error('图片大小不能超过 5MB!');
        return false;
      }
      return true;
    },
    handleImageError() {
      this.$message.error('图片上传失败');
    },
    removeImage() {
      this.$confirm('确定要删除这张图片吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.image = '';
        this.$message.success('图片已删除');
      }).catch(() => {});
    }
  }
};
</script>
<style scoped>
.system-bg {
  min-height: 80vh;
  background: linear-gradient(135deg, #f4f6fa 60%, #e0e7ff 100%);
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding: 48px 0;
  animation: fadeIn 0.8s;
}
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(30px);}
  to { opacity: 1; transform: none;}
}
.user-card {
  width: 1100px;
  border-radius: 18px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.10);
  background: rgba(255,255,255,0.95);
  transition: box-shadow 0.3s;
}
.card-header-vertical {
  display: flex;
  flex-direction: column;
  align-items: stretch;
  padding-bottom: 8px;
}
.header-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: left;
}
.header-btn-group {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  background: none;
  border-radius: 0;
  padding: 0;
  box-shadow: none;
}
.header-btn-group.right {
  justify-content: flex-end;
}
.header-btn-group .el-button {
  margin-right: 8px;
  height: 34px;
  font-size: 15px;
  padding: 0 18px;
  display: flex;
  align-items: center;
}
.header-btn-group .el-button:last-child {
  margin-right: 0;
}
.add-btn {
  background: linear-gradient(90deg, #6a82fb 0%, #fc5c7d 100%);
  border: none;
  color: #fff;
  font-weight: bold;
}
.add-btn:hover {
  background: linear-gradient(90deg, #fc5c7d 0%, #6a82fb 100%);
}
.user-table {
  border-radius: 10px;
  overflow: hidden;
  margin-bottom: 18px;
}
.user-table ::v-deep .el-table__row:hover {
  background: #f0f7ff !important;
  transition: background 0.2s;
}
.edit-btn {
  background: #fff;
  border: 1px solid #6a82fb;
  color: #6a82fb;
  margin-right: 8px;
  transition: all 0.2s;
  min-width: 55px;
}
.edit-btn:hover {
  background: #6a82fb;
  color: #fff;
}
.delete-btn {
  background: #fff;
  border: 1px solid #fc5c7d;
  color: #fc5c7d;
  transition: all 0.2s;
}
.delete-btn:hover {
  background: #fc5c7d;
  color: #fff;
}
.user-pagination {
  margin-top: 18px;
  text-align: right;
}
.user-pagination ::v-deep .el-pager li {
  border-radius: 6px;
  transition: background 0.2s;
}
.user-pagination ::v-deep .el-pager li.active {
  background: #6a82fb;
  color: #fff;
}
.fade-dialog ::v-deep .el-dialog__wrapper {
  animation: fadeIn 0.4s;
}
.custom-dialog ::v-deep .el-dialog {
  border-radius: 16px;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.18);
  background: #fafdff;
  padding-bottom: 0;
}
.dialog-form {
  padding: 12px 0 0 0;
}
.dialog-form ::v-deep .el-form-item {
  margin-bottom: 22px;
}
.dialog-footer {
  text-align: right;
  padding: 8px 0 8px 0;
}
.dialog-footer .el-button {
  min-width: 80px;
  border-radius: 6px;
  font-weight: 500;
  margin-left: 8px;
}
.dialog-footer .el-button--primary {
  background: linear-gradient(90deg, #6a82fb 0%, #fc5c7d 100%);
  border: none;
}
.dialog-footer .el-button--primary:hover {
  background: linear-gradient(90deg, #fc5c7d 0%, #6a82fb 100%);
}
.nowrap-label ::v-deep .el-form-item__label {
  white-space: nowrap;
}
.photo-upload {
  display: inline-block;
  vertical-align: middle;
}
.photo-upload-square {
  width: 80px;
  height: 80px;
  border: 1.5px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafbfc;
  cursor: pointer;
  transition: border-color 0.2s;
}
.photo-upload-square:hover {
  border-color: #6a82fb;
}
.photo-preview {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
  border: 1px solid #eee;
  cursor: pointer;
}
.photo-uploader-icon {
  font-size: 32px;
  color: #bbb;
}
.action-btn-group {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  gap: 12px;
  overflow: visible;
}
.action-btn-group .el-button {
  min-width: 55px;
  padding: 0 10px;
  height: 28px;
  line-height: 28px;
  box-sizing: border-box;
}
.action-btn-group .el-button:last-child {
  margin-right: 0;
}
.detail-btn {
  background: #fff;
  border: 1px solid #909399;
  color: #606266;
  border-radius: 6px;
  transition: all 0.2s;
}
.detail-btn:hover {
  background: #f4f6fa;
  color: #409EFF;
  border-color: #409EFF;
}
.detail-footer {
  margin-top: 32px;
  text-align: center;
}
.outline-btn {
  background: #fff;
  border: 1px solid #6a82fb;
  color: #6a82fb;
  margin-left: 8px;
  transition: all 0.2s;
}
.outline-btn:hover {
  background: #6a82fb;
  color: #fff;
}
</style>
